package com.pratices.rocketMQ;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class ConsumerDemo {
    public static void main(String[] args) throws InterruptedException, MQClientException, MQClientException {
        // 实例化消费者，并指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("myConsumerGroup");

        // 指定 NameServer 地址
        consumer.setNamesrvAddr("192.168.32.100:9876");

        // 订阅一个或多个主题和标签
        consumer.subscribe("myTopic", "*");

        // 注册消息监听者
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    System.out.printf("消费者收到消息: %s %n", new String(msg.getBody()));
                }
                // 返回消费状态：消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        // 启动消费者实例
        consumer.start();
        System.out.printf("消费者启动成功%n");
    }
}
